package com.tianyi.prototype;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.Date;

public class Paper implements Cloneable,Serializable{

	private String color = "White";
	private float length = 22.0f;
	private float width = 15.0f;
	private Date date=new Date();

	public String getColor() {
		return color;
	}

	public void setColor(String color) {
		this.color = color;
	}

	public float getLength() {
		return length;
	}

	public void setLength(float length) {
		this.length = length;
	}

	public float getWidth() {
		return width;
	}

	public void setWidth(float width) {
		this.width = width;
	}

	public Date getDate() {
		return date;
	}

	public void setDate(Date date) {
		this.date = date;
	}

	// 复印
	public void copy() {
		Paper p = (Paper) this.clone();
		System.out.println("原来纸张和复印出来的纸张是否相等:"+(p==this));
		System.out.println("原来纸张的长度和宽度分别为:"+this.getLength()+","+this.getWidth());
		System.out.println("复印出来的纸张的长度和宽度分别为:"+p.getLength()+","+p.getWidth());
		System.out.println("原来纸张的打印的时间是:"+this.getDate().getTime());
		System.out.println("复印出来的纸张打印的时间是:"+p.getDate().getTime());
	}

	
	//使用序列化和反序列化进行深度拷贝
	@Override
	protected Object clone() {
		ByteArrayOutputStream bos = null;
		ObjectOutputStream oos = null;
		ByteArrayInputStream bis = null;
		ObjectInputStream ois = null;
		try {
			// 序列化
			bos = new ByteArrayOutputStream();
			oos = new ObjectOutputStream(bos);
			oos.writeObject(this);

			// 反序列化
			bis = new ByteArrayInputStream(bos.toByteArray());
			ois = new ObjectInputStream(bis);
			Paper copy = (Paper) ois.readObject();
			copy.date = new Date();

			return copy;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		} finally {
			try {
				bos.close();
				oos.close();
				bis.close();
				ois.close();

			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}
